package com.newshub.app.ui.video

import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.newshub.app.R

class VideoPlayerActivity : AppCompatActivity() {

    companion object {
        const val EXTRA_VIDEO_URL = "extra_video_url"
        const val EXTRA_VIDEO_TITLE = "extra_video_title"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_player)
        
        // 设置全屏
        window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_FULLSCREEN or
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        )
        
        // 设置标题
        val videoTitle = intent.getStringExtra(EXTRA_VIDEO_TITLE) ?: "视频播放"
        val videoTitleView = findViewById<TextView>(R.id.videoTitle)
        videoTitleView.text = videoTitle
        
        // 从Intent获取视频URL
        val videoUrl = intent.getStringExtra(EXTRA_VIDEO_URL)
        
        // 添加调试日志
        android.util.Log.d("VideoPlayerActivity", "视频URL: $videoUrl")
        
        if (videoUrl.isNullOrEmpty()) {
            android.util.Log.e("VideoPlayerActivity", "视频URL为空")
            showError("视频URL无效")
            return
        }
        
        // 这里可以集成视频播放器（如ExoPlayer、MediaPlayer等）
        // 简单起见，我们使用WebView加载视频（实际项目中推荐使用ExoPlayer）
        setupWebView(videoUrl)
        
        // 退出按钮
        findViewById<View>(R.id.closeButton).setOnClickListener {
            onBackPressed()
        }
        
        // 切换全屏按钮
        findViewById<View>(R.id.fullscreenButton).setOnClickListener {
            toggleFullscreen()
        }
    }
    
    private fun setupWebView(videoUrl: String) {
        val webView = findViewById<android.webkit.WebView>(R.id.webView)
        
        // 启用JavaScript和媒体播放
        webView.settings.javaScriptEnabled = true
        webView.settings.mediaPlaybackRequiresUserGesture = false
        webView.settings.domStorageEnabled = true
        webView.settings.allowContentAccess = true
        webView.settings.allowFileAccess = true
        webView.settings.allowFileAccessFromFileURLs = true
        webView.settings.allowUniversalAccessFromFileURLs = true
        webView.settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        webView.settings.cacheMode = android.webkit.WebSettings.LOAD_DEFAULT
        webView.settings.setAppCacheEnabled(true)
        webView.settings.databaseEnabled = true

        
        // 设置WebViewClient
        webView.webViewClient = object : android.webkit.WebViewClient() {
            override fun shouldOverrideUrlLoading(view: android.webkit.WebView?, url: String?): Boolean {
                return false
            }
            
            override fun onPageFinished(view: android.webkit.WebView?, url: String?) {
                super.onPageFinished(view, url)
                android.util.Log.d("VideoPlayerActivity", "页面加载完成: $url")
            }
            
            override fun onReceivedError(view: android.webkit.WebView?, errorCode: Int, description: String?, failingUrl: String?) {
                super.onReceivedError(view, errorCode, description, failingUrl)
                android.util.Log.e("VideoPlayerActivity", "WebView错误: $description")
            }
        }
        
        // 使用更简单的HTML5播放器
        val html = """
            <!DOCTYPE html>
            <html>
            <head>
                <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
                <meta charset="UTF-8">
                <style>
                    * {
                        margin: 0;
                        padding: 0;
                        box-sizing: border-box;
                    }
                    body { 
                        background-color: #000; 
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        height: 100vh;
                        font-family: Arial, sans-serif;
                    }
                    .video-container {
                        width: 100%;
                        height: 100%;
                        position: relative;
                    }
                    video { 
                        width: 100%; 
                        height: 100%; 
                        object-fit: contain;
                        background-color: #000;
                    }
                    .error {
                        color: #fff;
                        text-align: center;
                        padding: 20px;
                        background-color: #333;
                        border-radius: 8px;
                        margin: 20px;
                    }
                    .loading {
                        color: #fff;
                        text-align: center;
                        padding: 20px;
                    }
                </style>
            </head>
            <body>
                <div class="video-container">
                    <video id="videoPlayer" controls preload="metadata">
                        <source src="$videoUrl" type="video/mp4">
                        您的浏览器不支持视频播放
                    </video>
                    <div id="loading" class="loading">正在加载视频...</div>
                    <div id="error" class="error" style="display: none;">
                        <h3>视频加载失败</h3>
                        <p>URL: $videoUrl</p>
                        <p>请检查网络连接或视频链接</p>
                    </div>
                </div>
                <script>
                    var video = document.getElementById('videoPlayer');
                    var loading = document.getElementById('loading');
                    var error = document.getElementById('error');
                    
                    function hideLoading() {
                        loading.style.display = 'none';
                    }
                    
                    function showError(message) {
                        hideLoading();
                        error.style.display = 'block';
                        error.innerHTML = '<h3>视频播放失败</h3><p>' + message + '</p><p>URL: $videoUrl</p>';
                    }
                    
                    video.addEventListener('loadstart', function() {
                        console.log('视频开始加载');
                        loading.textContent = '正在加载视频...';
                    });
                    
                    video.addEventListener('loadedmetadata', function() {
                        console.log('视频元数据加载完成');
                        hideLoading();
                    });
                    
                    video.addEventListener('canplay', function() {
                        console.log('视频可以播放');
                        hideLoading();
                    });
                    
                    video.addEventListener('error', function(e) {
                        console.error('视频加载错误:', e);
                        var errorMessage = '未知错误';
                        if (video.error) {
                            switch(video.error.code) {
                                case video.error.MEDIA_ERR_ABORTED:
                                    errorMessage = '视频播放被中止';
                                    break;
                                case video.error.MEDIA_ERR_NETWORK:
                                    errorMessage = '网络错误';
                                    break;
                                case video.error.MEDIA_ERR_DECODE:
                                    errorMessage = '视频解码错误';
                                    break;
                                case video.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
                                    errorMessage = '视频格式不支持';
                                    break;
                            }
                        }
                        showError(errorMessage);
                    });
                    
                    video.addEventListener('ended', function() {
                        console.log('视频播放结束');
                        setTimeout(function() {
                            window.history.back();
                        }, 2000);
                    });
                    
                    // 设置超时检测
                    setTimeout(function() {
                        if (video.readyState === 0) {
                            showError('视频加载超时');
                        }
                    }, 10000);
                </script>
            </body>
            </html>
        """
        
        android.util.Log.d("VideoPlayerActivity", "开始加载视频: $videoUrl")
        webView.loadDataWithBaseURL(videoUrl, html, "text/html", "UTF-8", null)
    }
    
    private fun toggleFullscreen() {
        val videoTitleView = findViewById<TextView>(R.id.videoTitle)
        if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            // 切换到全屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            videoTitleView.visibility = View.GONE
        } else {
            // 切换到竖屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            videoTitleView.visibility = View.VISIBLE
        }
    }
    
    override fun onBackPressed() {
        // 恢复竖屏
        if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        } else {
            super.onBackPressed()
        }
    }
    
    private fun showError(message: String) {
        val webView = findViewById<android.webkit.WebView>(R.id.webView)
        val errorHtml = """
            <!DOCTYPE html>
            <html>
            <head>
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <style>
                    body { 
                        margin: 0; 
                        padding: 20px; 
                        background-color: black; 
                        color: white;
                        font-family: Arial, sans-serif;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        height: 100vh;
                        text-align: center;
                    }
                    .error {
                        font-size: 18px;
                    }
                </style>
            </head>
            <body>
                <div class="error">
                    <h2>视频播放失败</h2>
                    <p>$message</p>
                    <p>请检查网络连接或视频链接</p>
                </div>
            </body>
            </html>
        """
        webView.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null)
    }
    
    override fun onDestroy() {
        // 释放WebView资源
        val webView = findViewById<android.webkit.WebView>(R.id.webView)
        webView.loadUrl("about:blank")
        webView.destroy()
        super.onDestroy()
    }
}